package com.prim.update.impl;

import com.prim.update.UpdateManager;
import com.prim.update.UpdateManager.Builder.RequestType;
import com.prim.update.callback.CommentCallback;
import com.prim.update.interfaces.ICheckInfo;
import com.prim.update.interfaces.IUpdateChecker;
import com.prim.update.interfaces.IUpdateExplorer;
import com.prim.update.state.StateType;
import com.prim.update.state.UpdateState;
import com.prim.update.utils.Utils;

/**
 * ================================================
 * 作    者：linksus
 * 版    本：1.0
 * 创建日期：3/5 0005
 * 描    述：具体实现者 检测版本更新
 * 修订历史：
 * ================================================
 */
public class UpdateChecker implements IUpdateChecker, CommentCallback {
    private IUpdateExplorer explorer;
    private ICheckInfo info;

    @Override
    public boolean checker(IUpdateExplorer explorer, ICheckInfo info) {
        this.explorer = explorer;
        this.info = info;
        UpdateState.setState(StateType.CHECK);
        try {
            if (explorer.getBuilder().type == RequestType.POST) {
                UpdateManager.getInstance().getHttpClient().enqueuePost(explorer.getBuilder().checkUrl, explorer.getBuilder().params, this);
            } else {
                String urlFromParams = "";
                if (explorer.getBuilder().params != null && !explorer.getBuilder().params.isEmpty()) {
                    urlFromParams = Utils.createUrlFromParams(explorer.getBuilder().checkUrl, explorer.getBuilder().params);
                } else {
                    urlFromParams = explorer.getBuilder().checkUrl;
                }
                UpdateManager.getInstance().getHttpClient().enqueueGet(urlFromParams, this);
            }
            return true;
        } catch (Exception e) {
            info.setError("网络请求异常：" + e.getMessage());
            explorer.stop();
            return false;
        }
    }

    @Override
    public void onSuccess(String result) {
        info.setInfo(result);
        explorer.doConvert();//交给下一个执行者 转换数据
    }

    @Override
    public void onError(String ex) {
        info.setError("网络请求异常：" + ex);
        explorer.stop();
    }

    @Override
    public void onCancelled() {
        info.setError("网络请求取消");
        explorer.stop();
    }

    @Override
    public void onFinished() {

    }
}
